const { app, Menu,Tray, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const AutoLaunch = require('auto-launch');
// const {  addEssay, changeEssayStatus, getAllEssay, getAllTodo, addTodo, changeTodoStatus, getBallData } = require('./utils/database.js')
const { createSuspensionWindow, createEssayWindow, createTodoWindow, createConfigWindow } = require("./window.js")
// Menu.setApplicationMenu(null);

// 开机自启
const autoLauncher = new AutoLaunch({
  name: app.getName(), // 应用名称（需唯一）
  path: app.getPath('exe'), // 自动获取应用路径
});

// 环境隔离
require('dotenv').config({
  path: path.join(__dirname, `.env.${process.env.NODE_ENV || 'development'}`)
});

// 访问环境变量
console.log(process.env.API_URL);

// 开发者热更新
try {
  require('electron-reloader')(module, {watchRenderer: true});
} catch (_) {}

// 悬浮球的一些设置
const suspensionConfig = {
  width: 85,
  height: 50,
}

// const suspensionConfig = {
//   width: 200,
//   height: 347,
// }

// 定义所有可能用到的页面
const pages = {
  suspensionWin: undefined,
  configWin: undefined,
}

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
  app.quit();
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', () => {
  pages.suspensionWin = createSuspensionWindow(suspensionConfig)

  //系统托盘
  // 创建系统托盘图标
  tray = new Tray(path.join(__dirname, './assets/edit-green.png'));

  // 设置托盘提示
  tray.setToolTip('Ns悬浮窗');

  // 创建上下文菜单
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '设置',
      click: () => {
        showConfig();
      }
    },
    {
      label: '退出',
      click: () => {
        appIsQuitting = true;
        app.quit();
      }
    }
  ]);

  // 关联菜单到托盘
  tray.setContextMenu(contextMenu);
  // 点击托盘图标切换窗口显示/隐藏（Windows/Linux）
  tray.on('click', () => {
    pages.suspensionWin.show();
  });
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    pages.suspensionWin = createSuspensionWindow(suspensionConfig)
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
function showConfig(){
  if (pages.configWin) {
    pages.configWin.close()
    pages.configWin = null
  }
  pages.configWin = createConfigWindow()
  pages.configWin.on('close', (e, data) => {
    pages.configWin = null
  })
}
// 主进程监听事件相关

ipcMain.on('quitApp', (e, data) => {
  app.quit();
})

ipcMain.on('showConfig', (e, data) => {
  showConfig()
})

ipcMain.on('ballWindowMove', (e, data) => {
  pages.suspensionWin.setBounds({ x: data.x, y: data.y, width: suspensionConfig.width, height: suspensionConfig.height })
  // pages.floatWin.setPosition(data.x, data.y)
})

// let suspensionMenu
// let topFlag = true
// ipcMain.on('openMenu', (e) => {
//   if (!suspensionMenu) {
//     suspensionMenu = Menu.buildFromTemplate([
//       {
//         label: '配置',
//         click: () => {
//           if (pages.configWin) {
//             pages.configWin.close()
//             pages.configWin = null
//           }
//           pages.configWin = createConfigWindow()
//           pages.configWin.on('close', (e, data) => {
//             pages.configWin = null
//           })
//         }
//       },
//       {
//         label: '置顶/取消',
//         click: () => {
//           topFlag = !topFlag
//           pages.suspensionWin.setAlwaysOnTop(topFlag)
//         }
//       },
//       {
//         label: '开发者工具',
//         click: () => {
//           pages.suspensionWin.webContents.openDevTools({ mode: 'detach' })
//         }
//       },
//       {
//         label: '重启',
//         click: () => {
//           app.quit()
//           app.relaunch()
//         }
//       },
//       {
//         label: '退出',
//         click: () => {
//           app.quit();
//         }
//       },
//     ]);
//   }
//   suspensionMenu.popup({});
// });

ipcMain.on('setFloatIgnoreMouse', (e, data) => {
  pages.suspensionWin.setIgnoreMouseEvents(data, { forward: true })
})

ipcMain.on('updateConfig', (e, data) => {
  pages.suspensionWin.webContents.send('config', data)
  if(pages.configWin){
    pages.configWin.webContents.send('config', data)
  }

})


// 开机自启动
ipcMain.on('changeAutoLauncher', (e, data) => {
  console.log("changeAutoLauncher data:",data)
  if (data){
    autoLauncher.enable()
        .then(() => console.log('enable auto launcher'))
        .catch(err => console.error('设置失败:', err));
  }else {
    // 禁用自启动
    autoLauncher.disable()
        .then(() => console.log('disable auto launcher'))
        .catch(err => console.error('禁用失败:', err));
  }

  // // 检查当前状态
// autoLauncher.isEnabled()
//     .then(enabled => console.log('当前状态:', enabled ? '已启用' : '未启用'));
})
